﻿using System;
using System.Windows.Forms;
using EasyModbus;

namespace RunningWavelet.DataGenerators
{
    /// <summary>
    ///     ThanksTO: http://easymodbustcp.net/
    /// </summary>
    public class WagoGenerator : GenerableBase
    {
        private readonly ModbusClient _modbusClient;

        public WagoGenerator()
        {
            _modbusClient = new ModbusClient();
        }

        public string WagoAddressIp
        {
            get { return _modbusClient.IPAddress; }
            set { _modbusClient.IPAddress = value; }
        }

        public int WagoPort
        {
            get { return _modbusClient.Port; }
            set { _modbusClient.Port = value; }
        }

        public int WagoTimeOut
        {
            get { return _modbusClient.ConnectionTimeout; }
            set { _modbusClient.ConnectionTimeout = value; }
        }

        public int WagoPollCycle { get; set; }
        public int WagoRegisterStart { get; set; }
        public int WagoRegisterCount { get; set; }

        public bool WagoConnect()
        {
            try
            {
                _modbusClient.Connect();
                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Ошибка подключения по ModbusTCP", MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
                return false;
            }
        }

        public void WagoDisconnect()
        {
            _modbusClient.Disconnect();
        }

        public int[] CheckRegisters(short r, short c)
        {
            if (_modbusClient.Connected == false)
                WagoConnect();
            try
            {
                var readHoldingRegisters = _modbusClient.ReadHoldingRegisters(r, c);
                return readHoldingRegisters;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            return null;
        }

        protected internal override double GenerateValue()
        {
            if (_modbusClient.Connected == false)
                WagoConnect();

            try
            {
                var readHoldingRegisters = _modbusClient.ReadHoldingRegisters(WagoRegisterStart, WagoRegisterCount);
                return readHoldingRegisters != null ? readHoldingRegisters[0] : 0;
            }
            catch (Exception)
            {
                throw;
            }
        }
    }
}